package xmysql

import (
	"database/sql"

	"gitee.com/githubdog/goci/libraries/clients/xssh"
	"gitee.com/githubdog/goci/tools/helper"

	"github.com/go-sql-driver/mysql"
)

// CheckConn 验证连接是否有效
func (db *DbSSH) checkConn(dbConf DBConf, sshConf xssh.SSHConf) bool {
	return db.ConnUUID != "" && db.ConnUUID == helper.Md5String(getDsnByConf(dbConf, protocolSSH)+sshConf.ToString())
}

// Conn 连接
func (db *DbSSH) Conn(dbConf DBConf, sshConf xssh.SSHConf) error {
	db.Conf = dbConf
	db.DSN = getDsnByConf(dbConf, protocolSSH)

	var err error
	if sshConf.KeyFile != "" {
		db.SSHClient, err = xssh.SSHConnWithKey(sshConf)
	} else {
		db.SSHClient, err = xssh.SSHConnWithPassword(sshConf)
	}
	// log.Printf("SSHConnWithKey: %s\n", err.Error())
	if err != nil {
		return err
	}

	mysql.RegisterDialContext(protocolSSH, (&xssh.ViaSSHDialer{
		Client: db.SSHClient,
	}).DialContext)
	// mysql.RegisterDial(protocolSSH, (&xssh.ViaSSHDialer{
	// 	Client: db.SSHClient,
	// }).Dial)
	if db.DbClient, err = sql.Open("mysql", db.DSN); err == nil {
		db.ConnUUID = helper.Md5String(db.DSN + sshConf.ToString())
	}
	return err
}

// Close 关闭
func (db *DbSSH) Close() {
	if err := db.DbClient.Close(); err == nil {
		db.SSHClient.Close()
	}
}
